const app = getApp();
Page({
  data: {
    genderList: ['雄性', '雌性'],
    kindList: ['猫', '狗'],
    pets: []
  },
  toggleActions(e) {
    const index = e.currentTarget.dataset.index;
    const pets = this.data.pets;
    pets[index].showActions = !pets[index].showActions;
    this.setData({
      pets
    });
  },
     // 编辑宠物逻辑
  editPet(e) {
    const index = e.currentTarget.dataset.index;
    // console.log(this.data.pets[index]);
    const pet =  this.data.pets[index]
    console.log(pet);
    // console.log(pet);
    wx.navigateTo({
      url: `/pages/petinfo/edit/edit?name=${pet.name}&gender=${pet.sex}&kindid=${pet.kindid}&age=${pet.age}&image=${pet.image}&id=${pet.id}`,
    });
  },
  //删除
  deletePet(e) {
    var that = this;
    const index = e.currentTarget.dataset.index;
    const id  = that.data.pets[index].id
    console.log(id);
    wx.request({
      url: 'http://127.0.0.1:7001/api/user/deletepet',
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      method: 'POST',
      data: {
        petid: id
      }, 
      success: function (res) {
        console.log(res.data);
        that.setData({
          pets:[]
        })
        that.onLoad()
      }
    })
  },
  onLoad(options) {
    var that = this;
    var openid = wx.getStorageSync('openid')
    wx.request({
      url: 'http://127.0.0.1:7001/api/user/petinfo',
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      method: 'GET',
      data: {
        ownerid: openid
      }, 
      success: function (res) {
        console.log(res.data);
        const data = res.data.data.result
        console.log(data);
        for(var i = 0; i <data.length; i++){
          // console.log(data[i]);   
          const {id,age,name,sex,kindid,src} = data[i]
          // console.log(src);
          const base64 = wx.arrayBufferToBase64(new Uint8Array(src.data));
          const image ='data:image/png;base64,' + base64
          var pets = that.data.pets;
          pets.push({id:id,age:age,name:name,sex:sex,kindid:kindid,image:image})
          // console.log(pets);
          that.setData({
            pets:pets
          })
        }
        app.globalData.pets = that.data.pets;
      }
    })
  },
  onAddTap: function () {
    // 跳转到添加页面
    wx.navigateTo({
      url: '/pages/petinfo/add/add',
    });
  },
})
